const Router = require('koa-router');
const db = require('../database/config/db');
const bcrypt = require('bcrypt');
const saltRounds = 10;
const tableName = 'user';

const router = new Router();
router.get('/', async ctx => {
    ctx.body = '这是用户操作首页'
});
// 已登录账号：admin admin2019
router.post('/register', async ctx => {
    console.log(ctx.request.body);
    let data = ctx.request.body;

    let queryUser = await db.QUERY_DATA(tableName, {username: data.username});
    console.log(queryUser);
    if (queryUser.length > 0) {
        ctx.body = {
            code: 1,
            message: "用户名已存在"
        }
        return;
    }
    // 加盐
    var salt = bcrypt.genSaltSync(saltRounds);
    // 生成hash密码
    var hash = bcrypt.hashSync(data.password, salt);
    data.password = hash;
    await db.INSERT_DATA('user', data).then(async () => {
        let result = await db.QUERY_FIRST(`SELECT * FROM user WHERE username='${data.username}'`);
        ctx.body = {
            code: 200,
            message: '注册成功',
            data: {
                userInfo: result
            }
        }
    }, err => {
        ctx.body = {
            code: 500,
            message: err
        }
    });
})

router.post('/login', async ctx => {
    let loginUser = ctx.request.body;
    console.log(loginUser);
    let username = loginUser.username;
    let password = loginUser.password;

    await db.QUERY_FIRST(`SELECT * FROM ${tableName} WHERE username=?`, [username]).then(async result => {
        console.log(result);
        if (result) {
            let pwdhash = result.password;
            await comparePassword(password, pwdhash).then(isMatch => {
                ctx.body = {
                    code: 200,
                    message: isMatch,
                    data: {
                        userInfo: result,
                    }
                }
            }).catch(err => {
                // console.log(err);
                ctx.body = {
                    code: 500,
                    message: err
                }
            })
        } else {
            ctx.body = {
                code: 200,
                message: '用户名不存在',
            }
        }
    }).catch(err => {
        console.log(err);
        ctx.body = {
            code: 500,
            message: err
        }
    });
});

// ====================

// 看密码是否匹配
// _password:用户输入的密码
// password:数据库查询的hash密码
function comparePassword(_password, password) {
    return new Promise((resolve, reject) => {
        bcrypt.compare(_password, password, (err, isMatch) => {
            if (!err) resolve(isMatch);
            else reject(err);
        })
    })
}

module.exports = router;